package com.sunday.common.mq.kafka.study.spring.e10_Pausing_Resuming_Listener_Containers;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.TopicPartition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @Autowired
    private KafkaListenerEndpointRegistry endpointRegistry;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {

        sendMsg(topic, key);
        TimeUnit.SECONDS.sleep(5);

        log.info("pausing");
        endpointRegistry.getListenerContainer("myId_6").pause();

        TimeUnit.SECONDS.sleep(5);
        sendMsg(topic, key);

        TimeUnit.SECONDS.sleep(5);
        log.info("resuming");
        endpointRegistry.getListenerContainer("myId_6").resume();

        TimeUnit.SECONDS.sleep(5);
        sendMsg(topic, key);

        /** https://docs.spring.io/spring-kafka/docs/current/reference/html/#pause-resume */
        TimeUnit.SECONDS.sleep(5);
        log.info("partition pausing");
        endpointRegistry.getListenerContainer("myId_6").pausePartition(new TopicPartition("topic6", 2));

        TimeUnit.SECONDS.sleep(5);
        sendMsg(topic, key);

        TimeUnit.SECONDS.sleep(5);
        log.info("partition resuming");
        endpointRegistry.getListenerContainer("myId_6").resumePartition(new TopicPartition("topic6", 2));

    }

    public void sendMsg(String topic, String key) throws ExecutionException, InterruptedException {
        CompletableFuture<SendResult<Object, Object>> future = kafkaTemplate.send(topic, key, key);
        log.info("[send result] : {}", future.get());
    }

    @KafkaListener(
            id = "myId_6",
            topics = "topic6",
            clientIdPrefix = "TEST"
    )
    public void listen6(String in) {
        log.info("======================== {}", in);
    }


}
